package com.life.xxx.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.life.xxx.entity.LifeUser;
import com.life.xxx.mapper.LifeUserMapper;
import com.life.xxx.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Component
public class LoginFilter implements Filter {

    @Autowired
    private LifeUserMapper lifeUserMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // ✅ 1. 获取请求路径，跳过公开接口（如登录、注册）
        String requestURI = request.getRequestURI();
        if (isPublicEndpoint(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // ✅ 2. 获取 Authorization 头
        String authHeader = request.getHeader("Authorization");
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"error\": \"Missing or invalid Authorization header\"}");
            return;
        }

        // ✅ 3. 提取 token
        String token = authHeader.substring(7); // 去掉 "Bearer "

        // ✅ 4. 从 token 中提取 userId（先不验证，仅解析结构）
        String userId = JwtUtil.getUserIdFromRefreshToken(token);
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"error\": \"Invalid token format\"}");
            return;
        }
        // ✅ 5. 根据 userId 查询用户密码哈希（模拟数据库查询）
        QueryWrapper<LifeUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        LifeUser user = lifeUserMapper.selectOne(wrapper);
        String passwordHash = user.getPassword();
        String salt = user.getSalt();
        if (passwordHash == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"error\": \"User not found\"}");
            return;
        }

        // ✅ 6. 使用 JwtUtil 验证 token 是否有效（签名 + 过期）
        boolean isValid = JwtUtil.validateAccessToken(passwordHash, salt, token);
        if (!isValid) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"error\": \"Invalid or expired token\"}");
            return;
        }

        // ✅ 7. 【关键】判断是否需要无感刷新（比如剩余时间 < 5分钟）
        if (JwtUtil.shouldRefresh(token)) {
            try {
                // 生成新 Access Token
                String newToken = JwtUtil.generateAccessToken(passwordHash, salt, userId);
                // 通过响应头返回新 Token
                response.setHeader("New-Access-Token", newToken);
            } catch (Exception e) {
                // 记录日志即可，不影响原请求
                e.printStackTrace();
            }
        }

        // ✅ 8. 验证通过，将用户信息放入请求属性，供 Controller 使用
        request.setAttribute("userId", userId);

        // ✅ 9. 放行，继续执行后续过滤器或 Controller
        filterChain.doFilter(servletRequest, servletResponse);
    }

    // ✅ 判断是否为公开接口
    private boolean isPublicEndpoint(String requestURI) {
        return requestURI.startsWith("/user/");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}